package com.guli.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.pojo.vo.StatusCodeEnum;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月27日 下午9:59:27
 */
public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public static final String CODE = "code";

    private R() {
        put(CODE, StatusCodeEnum.SUCCESS.getCode());
    }

    public R setData(Object data0) {
        this.put("data0", data0);
        return this;
    }

    public <T> T getData(TypeReference<T> typeReference) {
        Object data0 = this.get("data0");

        String jsonString = JSON.toJSONString(data0); // 要先转为jsonString，否则 object 本质上是 LinkedHashMap

        T t = JSON.parseObject(jsonString, typeReference); // 只能解析json字符串，不能解析 LinkedHashMap

        return t;
    }

    public String getDefaultData() {

        Object data0 = this.get("data0");

        return data0.toString();
    }

    public static R error() {
        return error(StatusCodeEnum.UNKNOW_EXCEPTION);
    }

    public static R error(String msg) {
        return error(500, msg);
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.put(CODE, code);
        r.putMsg(msg);
        return r;
    }

    public static R error(StatusCodeEnum statusCodeEnum) {
        R r = new R();
        r.put(CODE, statusCodeEnum.getCode());
        r.putMsg(statusCodeEnum.getMsg());
        return r;
    }

    public static R ok(String msg) {
        R r = new R();
        r.putMsg(msg);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    public static R redirect(String url, String finalUrl) {
        R r = new R();
        r.put("code", StatusCodeEnum.REDIRECT_TO_URL.getCode());
        r.put("url", url);
        r.put("finalUrl", finalUrl);
        return r;
    }

    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public Integer getCode() {

        Object o = this.get(CODE);

        return Integer.parseInt(o.toString());
    }

    public R putMsg(String msg) {
        this.put("msg", msg);
        return this;
    }

    public String getMsg() {
        Object msg = this.get("msg");


        return ObjectUtils.isEmpty(msg) ? null : msg.toString();
    }
}
